<?php
require "connect_database.php";
session_start();

$username = "";
$password = "";
$validation_username = true;
$validation_username_message = "";
$validation_password = true;
$validation_password_message = "";
$username_postback_flag = false;
$username_postback = "";
$user_id = "";
$user_name = "";
$verification_login = true;
$verification_login_message = "";
$login_status = false;
$_SESSION['login'] = false;

if((isset($_SESSION['login']))&&($_SESSION['login']=="true"))
{
	$login_status = true;
}
else
{
	if(isset($_POST['username'])){$username = $_POST['username'];}
	if(isset($_POST['password'])){$password = $_POST['password'];}

	/* Validation */
	if(empty($username)){
		$validation_username = false;
		$validation_username_message = "Please fill-in your ID and password completely";
	}
	else if (empty($password)){
		$username_postback_flag = true;
		$username_postback = $username;
		$validation_password = false;
		$validation_password_message = "Please fill-in your ID and password completely";
	}
	else if (strlen(trim($username)) == 0)
	{
		$validation_username = false;
		$validation_username_message = "Please don't key-in white space only";
	}
	else if (strlen(trim($password)) == 0)
	{
		$username_postback_flag = true;
		$username_postback = $username;
		$validation_password = false;
		$validation_password_message = "Please don't key-in white space only";
	}
	else
	{
		$sql_login_query = "SELECT `user_id`, `user_name` FROM `user` WHERE `username`='$username' AND `password`='$password'";
		$sql_login_result = mysqli_query($connect, $sql_login_query);

		if((mysqli_num_rows($sql_login_result)) == 0)
		{
			$username_postback_flag = true;
			$username_postback = $username;
			$verification_login = false;
			$verification_login_message = "Invalid Account";
		}
		else if ((mysqli_num_rows($sql_login_result)) != 0)
		{
			$get_login_details = mysqli_fetch_array($sql_login_result, MYSQLI_ASSOC);
			$user_id = $get_login_details['user_id'];
			$user_name = $get_login_details['user_name'];
			$login_status = true;
			$_SESSION['user_id'] = $user_id;
			$_SESSION['user_name'] = $user_name;
			$_SESSION['login'] = true;
		}
	}
}
?>
<?php
	// Collect all json data
	$jsonArray = array(
		'validation_username' => $validation_username,
		'validation_username_message' => $validation_username_message,
		'validation_password' => $validation_password,
		'validation_password_message' => $validation_password_message,
		'username_postback_flag' => $username_postback_flag,
		'username_postback' => $username_postback,
		'user_id' => $user_id,
		'user_name' => $user_name,
		'login_status' => $login_status,
		'verification_login' => $verification_login,
		'verification_login_message' => $verification_login_message,
	);

	// Set json data as valid
	$jsonArray['status'] = true;

	// Build json object and echo out
	echo json_encode($jsonArray);

	mysqli_close($connect);
?>